package com.flea.mvc.controller;

import com.flea.mvc.model.Person;
import com.flea.mvc.model.PersonJson;
import com.flea.mvc.service.PersonService;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by lhl on 2014/4/18.
 */
@RestController
@RequestMapping("/user")
public class PersonController {
    private static  final Logger LOGGER=Logger.getLogger(PersonController.class);
    @Autowired
    private PersonService personService;


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<Person> getPerson(@PathVariable("id") Integer id) {
        Person person = personService.findPerson(id);
        if (null == person) {
            return new ResponseEntity<Person>(person, HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<Person>(person, HttpStatus.OK);
        }
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public void addPerson(@RequestBody Person person, HttpServletRequest request, HttpServletResponse response) {
        personService.insertPerson(person);
        response.setHeader("Location", request.getRequestURL().append("/").append(person.getId()).toString());
    }
    @RequestMapping(value = "{id}",method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.NO_CONTENT)
  public void  deletePerson(@PathVariable("id")Integer id){
        personService.deletePerson(id);

  }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET,produces = "application/json")
    public ResponseEntity<PersonJson> getPersonJson(@PathVariable("id") Integer id) {
        Person person = personService.findPerson(id);
        PersonJson personJson=new PersonJson();
        if (null == person) {
            return new ResponseEntity<PersonJson>(personJson, HttpStatus.NOT_FOUND);
        } else {
            BeanUtils.copyProperties(person,personJson);
            HttpHeaders reponseHeaders =new HttpHeaders();
//          //  reponseHeaders.setContentType(MediaType.APPLICATION_JSON);
//            reponseHeaders.setContentType(MediaType.parseMediaType("text/html; charset=utf-8"));
            return new ResponseEntity<PersonJson>(personJson,reponseHeaders, HttpStatus.OK);
        }
    }
}
